package com.itheima.jobs;

import constant.RedisConstant;
import org.springframework.beans.factory.annotation.Autowired;
import redis.clients.jedis.JedisPool;
import utils.QiniuUtils;

import java.util.Set;

/**
 * 自定义Job类，实现定时清理图片
 */
public class ClearImgJob {
    
    @Autowired
    private JedisPool jedisPool;
    
    public void clearImg(){
        //根据Redis数据库中保存的两个set集合差值，获得垃圾图片的集合
        System.out.println("进入到clearImg方法==============");
        System.out.println("RedisConstant.SETMEAL_PIC_RESOURCES:" + RedisConstant.SETMEAL_PIC_RESOURCES);
        System.out.println("RedisConstant.SETMEAL_PIC_DB_RESOURCES:" + RedisConstant.SETMEAL_PIC_DB_RESOURCES);
        
        if(RedisConstant.SETMEAL_PIC_RESOURCES != null && RedisConstant.SETMEAL_PIC_DB_RESOURCES != null){
            Set<String> set =jedisPool.getResource().sdiff(RedisConstant.SETMEAL_PIC_RESOURCES,
                            RedisConstant.SETMEAL_PIC_DB_RESOURCES);
    
            System.out.println("SETMEAL_PIC_RESOURCES: " + jedisPool.getResource().smembers(RedisConstant.SETMEAL_PIC_RESOURCES));
            System.out.println("SETMEAL_PIC_DB_RESOURCES: " + jedisPool.getResource().smembers(RedisConstant.SETMEAL_PIC_DB_RESOURCES));
            System.out.println("得到差值======set:" + set);
    
            if(set != null){
                for(String picName : set){
                    //删除七牛云服务器上的图片
                    System.out.println("要删除的图片名为：" + picName);
                    if(QiniuUtils.deleteFileFromQiniu(picName)){
                        System.out.println("已经从七牛云删除==================");
                
                        //从Redis集合中删除图片名称
                        jedisPool.getResource().srem(RedisConstant.SETMEAL_PIC_RESOURCES,picName);
                
                        System.out.println("已经从Redis集合PIC_中删除图片名称");
                    }else{
                        System.out.println("删除七牛云服务器上的图片删除失败");
                    }
            
                }
            }
        }else{
            System.out.println("redis数据为null,不做任何处理");
        }
        
    }
}
